package com.mathslogica;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

public class ML {
	/**
	 * Extract video or playlist id from the String returned by (entry).getId()
	 * 
	 * @param id
	 * @return
	 */

	public static Map<String, String> getParamMap(String url) {
		Map<String, String> map = new HashMap<String, String>();
		if (url.indexOf('?') > -1) {
			url = url.split("?")[1];
		}

		String[] array = url.split("&");
		for (int i = 0; i < array.length; i++) {
			String[] temp = array[i].split("=");
			map.put(temp[0], temp[1]);
		}
		return map;
	}

	public static String getParam(String url, String param) {
		url = url.substring(url.indexOf('?') + 1);

		String[] array = url.split("&");
		for (int i = 0; i < array.length; i++) {
			String[] temp = array[i].split("=");
			if (temp[0].equals(param))
				return temp[1];
		}
		return null;
	}

	public static String getUrlContent(String url) throws IOException {
		URL oracle = new URL(url);

		URLConnection yc = oracle.openConnection();
		BufferedReader in = new BufferedReader(new InputStreamReader(
				yc.getInputStream()));
		String inputLine = "";
		String content = "";
		while ((inputLine = in.readLine()) != null)
			content += inputLine;
		in.close();
		return content;
	}

	public static String md5(String number) {
		byte[] defaultBytes = number.getBytes();
		StringBuffer hexString = new StringBuffer();
		try {
			MessageDigest algorithm = MessageDigest.getInstance("MD5");
			algorithm.reset();
			algorithm.update(defaultBytes);
			byte messageDigest[] = algorithm.digest();

			for (int i = 0; i < messageDigest.length; i++) {
				hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
			}

		} catch (NoSuchAlgorithmException nsae) {

		}
		return hexString.toString();
	}

}
